<template>
  <a-form-model
    ref="ruleForm"
    :model="form"
    :rules="rules"
    layout="horizontal"
    class="AsteriskAfter newEditStyle rightDrawerWithoutCol newEditEcuForm"
  >
    <!-- 车型 -->
    <a-row :gutter="36">
      <a-col :md="24" :sm="24">
        <a-form-model-item :label="$t('vehicleModel')" prop="modelCode">
          <car-model-code-select
            mode="default"
            :query="{ time:instantUpdateTime}"
            :has-all="false"
            :default-value="form.modelCode"
            :disabled="!!recordData.id"
            @changeoption="changeoption($event, 'modelCode')"
          ></car-model-code-select>
        </a-form-model-item>
      </a-col>
    </a-row>
    <!-- 车型下对应的款型列表 -->
    <div class="trimLevelBox commonTableSty" style="margin-bottom:16px" v-show="false">
      <trim-level-config
        :modelCode="form.modelCode"
        :ecu-id="recordData.id"
        ref="trimLevelConfigRef"
        :ecuModels="form.ecuModels"
      ></trim-level-config>
    </div>
    <!-- 零件ID 零件名称-->
    <a-row :gutter="36">
      <a-col :md="12" :sm="24">
        <a-form-model-item prop="ecuModuleId">
          <template slot="label">
            {{ $t('partNumber') }}
            <question-mark-tip
              :tip-title="$t('partNumberTip')"
              :popupContainer="$commonFun.getPopupContainer"
            ></question-mark-tip>
          </template>
          <a-input  :maxLength="40" :disabled="!!recordData.id" v-model="form.ecuModuleId" />
        </a-form-model-item>
      </a-col>
      <a-col :md="12" :sm="24">
        <a-form-model-item :label="$t('partName')" prop="name">
          <a-input  :maxLength="25" v-model="form.name" :disabled="!!recordData.id" />
        </a-form-model-item>
      </a-col>
      <!--    </a-row>-->
      <!--软件编码 供应商 -->
      <!--    <a-row :gutter="36">-->
      <a-col :md="12" :sm="24">
        <a-form-model-item :label="$t('softwareCoding')" prop="softwareCode">
          <a-input  :maxLength="18" :disabled="!!recordData.id" v-model="form.softwareCode" />
        </a-form-model-item>
      </a-col>
      <a-col :md="12" :sm="24">
        <a-form-model-item :label="$t('supplier')" prop="supplierId">
          <a style="position: absolute;right: 0;top: -38px;" @click="editSupplier" v-if="!recordData.id || !form.supplierId">{{ $t('edit') }}</a>
          <supplier-select
            mode="default"
            :default-value="form.supplierId"
            :disabled="!!recordData.id && !!formDataCopy.supplierId"
            @changeoption="changeoption($event, 'supplierId')"
          ></supplier-select>
        </a-form-model-item>
      </a-col>
      <!--    </a-row>-->
      <!-- 烧写类型  烧写条件 -->
      <!--    <a-row :gutter="36">-->
      <a-col :md="12" :sm="24">
        <a-form-model-item :label="$t('sxType')" prop="ecuReprogramType">
          <a-select
            v-model="form.ecuReprogramType"
            optionFilterProp="children"
            :filterOption="$commonFun.filterOption"
            showSearch
            allow-clear
            @change="changeEcuReprogramType"
          >
            <a-select-option
              v-for="(item, index) in ecuReprogramTypeDictCode"
              :key="index"
              :value="item.value"
              :title="item.name"
            >{{ item.name }}</a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
      <!--诊断id 子诊断id-->
      <!--    <a-row :gutter="36">-->
      <a-col :md="12" :sm="24">
        <a-form-model-item prop="ecuDiaId">
          <template slot="label">
            {{ $t('diagnosisID') }}
            <question-mark-tip
              :tip-title="form.ecuReprogramType=== 'ethernet'?'格式举例：xxx/xxx(请求ID/应答ID)':'格式举例：xxx/xxx(请求ID/应答ID)，应答ID=请求ID+8'"
              :popupContainer="$commonFun.getPopupContainer"
            ></question-mark-tip>
          </template>
          <a-input  :maxLength="7" :disabled="(!!recordData.id && !!formDataCopy.ecuDiaId) || !form.ecuReprogramType" v-model="form.ecuDiaId" />
        </a-form-model-item>
      </a-col>
      <a-col :md="12" :sm="24">
        <a-form-model-item :label="$t('softDid')" prop="ecuDid">
          <a-input  :maxLength="9" v-model="form.ecuDid" :disabled="!!recordData.id && !!formDataCopy.ecuDid" />
        </a-form-model-item>
      </a-col>
      <!-- 硬件版本DID -->
      <a-col :md="12" :sm="24">
        <a-form-model-item :label="$t('ecuHardDid')" prop="ecuHardDid" required>
          <a-input  :maxLength="4" v-model="form.ecuHardDid" :disabled="!!recordData.id && !!formDataCopy.ecuHardDid" />
        </a-form-model-item>
      </a-col>
      <!-- 是否有文件系统 -->
      <a-col :md="12" :sm="24">
        <a-form-model-item prop="hasFileSystem" label="是否有文件系统">
          <a-select
            v-model="form.hasFileSystem"
            :placeholder="$t('pleaseSelect')"
            optionFilterProp="children"
            allow-clear
          >
            <a-select-option :value="1">{{ $t('yes') }}</a-select-option>
            <a-select-option :value="0">{{ $t('no') }}</a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
      <!-- 是否智驾ECU -->
      <a-col :md="12" :sm="24">
        <a-form-model-item prop="idrive" label="是否智驾ECU">
          <a-select
            v-model="form.idrive"
            optionFilterProp="children"
            allow-clear
          >
            <a-select-option :value="1">{{ $t('yes') }}</a-select-option>
            <a-select-option :value="0">{{ $t('no') }}</a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
      <!--    </a-row>-->
      <!-- 高低压模块 是否高压电源模块 -->
      <!--    <a-row :gutter="36">-->
      <a-col :md="12" :sm="24">
        <a-form-model-item :label="$t('gdymk')" prop="hlvFlag">
          <a-select
            v-model="form.hlvFlag"
            optionFilterProp="children"
            :filterOption="$commonFun.filterOption"
            showSearch
            allow-clear
          >
            <a-select-option
              v-for="(item, index) in hlvFlagDictCode"
              :key="index"
              :value="item.value"
              :title="item.name"
            >{{ item.name }}</a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
      <a-col :md="12" :sm="24">
        <a-form-model-item :label="$t('isGydymk')" prop="hvPowerFlag">
          <a-select
            v-model="form.hvPowerFlag"
            optionFilterProp="children"
            :filterOption="$commonFun.filterOption"
            showSearch
            allow-clear
          >
            <a-select-option
              v-for="(item, index) in hvPowerFlagDictCode"
              :key="index"
              :value="item.value"
              :title="item.name"
            >{{ item.name }}</a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
      <!--    </a-row>-->
      <!-- ECU IP ECU端口 -->
      <!--      <a-row :gutter="36">-->
      <a-col :md="12" :sm="24" v-if="verifyIPReprogramType.includes(form.ecuReprogramType)">
        <a-form-model-item prop="ecuIp">
          <template slot="label">
            <span
              :class="verifyIPReprogramType.includes(form.ecuReprogramType) ? 'requiredSty' : ''"
            >{{ `${$t('lingjian')} IP` }}</span>
          </template>
          <a-input  :maxLength="15" v-model="form.ecuIp"/>
        </a-form-model-item>
      </a-col>
<!--      v-if="verifyIPReprogramType.includes(form.ecuReprogramType)"-->
      <a-col :md="12" :sm="24" v-if="verifyIPReprogramType.includes(form.ecuReprogramType)">
        <a-form-model-item prop="ecuPort">
          <template slot="label">
            <span>{{ $t('ljPort') }}</span>
          </template>
          <a-input v-model="form.ecuPort" :maxLength="5"/>
        </a-form-model-item>
      </a-col>
      <!--      </a-row>-->
      <a-col :md="12" :sm="24">
        <a-form-model-item prop="ecuUpdateStyle">
          <template slot="label">
            <span>{{ $t('sxStyle') }}</span>
          </template>
          <a-select
            v-model="form.ecuUpdateStyle"
            optionFilterProp="children"
            :filterOption="$commonFun.filterOption"
            showSearch
            allow-clear
          >
            <a-select-option
              v-for="(item, index) in ecuUpdateStyleDictCode"
              :key="index"
              :value="item.value || ''"
              :title="item.name"
            >{{ item.name }}</a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
      <!--    </a-row>-->
      <!-- 烧写方式 差分策略 -->
      <!--    <a-row :gutter="36">-->
      <a-col :md="12" :sm="24">
        <a-form-model-item prop="ecuReprogramWay">
          <template slot="label">
            <span>{{ $t('sxWay') }}</span>
          </template>
          <a-select
            v-model="form.ecuReprogramWay"
            optionFilterProp="children"
            :filterOption="$commonFun.filterOption"
            showSearch
            allow-clear
            @change="clickOptionsWay"
          >
            <a-select-option
              v-for="(item, index) in ecuReprogramWayDictCode"
              :key="index"
              :value="item.value || ''"
              :title="item.name"
            >{{ item.name }}</a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
      <!-- 是否下发源版本包 -->
      <a-col :md="12" :sm="24">
        <a-form-model-item prop="needSourcePkg" label="是否下发源版本包">
          <a-select
            v-model="form.needSourcePkg"
            optionFilterProp="children"
            allow-clear
          >
            <a-select-option :value="1">{{ $t('yes') }}</a-select-option>
            <a-select-option :value="0">{{ $t('no') }}</a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
      <a-col :md="12" :sm="24">
        <a-form-model-item prop="encryptType">
          <template slot="label">
            {{ $t('encryption') }}
            <question-mark-tip
              tip-title="在线制作差分包时，MDC,DX,IDC等模块存在不同差分策略，请根据ECU实际情况选择差分策略。"
              :popupContainer="$commonFun.getPopupContainer"
            ></question-mark-tip>
          </template>
          <a-select
            v-model="form.encryptType"
            optionFilterProp="children"
            @change="changeEncryptType"
            :filterOption="$commonFun.filterOption"

            showSearch
            allow-clear
          >
            <a-select-option
              v-for="(item, index) in ecuEncryptTypeDictCode"
              :key="index"
              :value="parseInt(item.value, 10)"
              :title="item.name"
            >{{ item.name }}</a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
      <a-col :md="12" :sm="24">
        <a-form-model-item :label="'零部件编码'" prop="partCode">
          <a-input  :maxLength="20" v-model="form.partCode" />
        </a-form-model-item>
      </a-col>
      <a-col :md="12" :sm="24">
        <a-form-model-item :label="'模块主芯片'" prop="moduleMainChip">
          <a-input  :maxLength="30" v-model="form.moduleMainChip" />
        </a-form-model-item>
      </a-col>
      <!-- 操作系统 -->
      <a-col :md="12" :sm="24">
        <a-form-model-item :label="$t('OS')" prop="platform">
          <a-input  :maxLength="30" v-model="form.platform" />
        </a-form-model-item>
      </a-col>
      <!-- KeyK -->
      <a-col :md="12" :sm="24">
        <a-form-model-item :label="'KeyK'" prop="securityKey">
          <a-input :maxLength="10" v-model="form.securityKey" />
        </a-form-model-item>
      </a-col>
      <!-- 子项目 -->
      <a-col :md="12" :sm="24">
        <a-form-model-item :label="'子项目'" prop="childItem">
          <a-input  :maxLength="20" v-model="form.childItem" />
        </a-form-model-item>
      </a-col>
      <!--    </a-row>-->
      <!-- 是否验证Config.xml 操作系统 -->
      <!--    <a-row :gutter="36">-->
      <!-- 是否验证Config.xml -->
      <a-col :md="12" :sm="24">
        <a-form-model-item prop="checkConfig">
          <template slot="label">
            {{ $t('isVerifyConfigxml') }}
            <question-mark-tip
              :tip-title="$t('isVerifyConfigxmlTip')"
              :popupContainer="$commonFun.getPopupContainer"
            ></question-mark-tip>
          </template>
          <a-select
            v-model="form.checkConfig"
            :placeholder="$t('pleaseSelect') + $t('isVerifyConfigxml').toLowerCase()"
            optionFilterProp="children"
            allow-clear
          >
            <a-select-option :value="1">{{ $t('yes') }}</a-select-option>
            <a-select-option :value="0">{{ $t('no') }}</a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
      <!-- 是否有配置文件 -->
      <a-col :md="12" :sm="24">
        <a-form-model-item prop="hasConfig" label="是否有配置文件">
          <a-select
            v-model="form.hasConfig"
            :disabled="!!recordData.id && ![null,undefined].includes(formDataCopy.hasConfig)"
            :placeholder="$t('pleaseSelect')"
            @change="clearConfigValidate"
            optionFilterProp="children"
            allow-clear
          >
            <a-select-option :value="1">{{ $t('yes') }}</a-select-option>
            <a-select-option :value="0">{{ $t('no') }}</a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
      <!--    </a-row>-->

      <!-- 配置文件DID  配置文件软件编码 -->
      <!--    <a-row :gutter="36">-->
      <a-col :md="12" :sm="24" v-if="form.hasConfig != '0'">
        <a-form-model-item prop="ecuConfigDid">
          <template slot="label">
            <span :class="form.hasConfig == '1' ? 'requiredSty' : ''">{{ $t('configurationFile') }}</span>
          </template>
          <a-input  :maxLength="20"
            :disabled="(!!recordData.id && !!formDataCopy.ecuConfigDid) || form.hasConfig == '0'"
            v-model="form.ecuConfigDid"
          />
        </a-form-model-item>
      </a-col>
      <a-col :md="12" :sm="24" v-if="form.hasConfig != '0'">
        <a-form-model-item prop="configSoftwareCode">
          <template slot="label">
            <span
              :class="form.hasConfig == '1' ? 'requiredSty' : ''"
            >{{ $t('configurationFileCode') }}</span>
          </template>
          <a-input  :maxLength="18"
            :disabled="(!!recordData.id && !!formDataCopy.configSoftwareCode) || form.hasConfig == '0'"
            v-model="form.configSoftwareCode"
          />
        </a-form-model-item>
      </a-col>
    </a-row>
  </a-form-model>
</template>
<script>
import TableEllipsis from '@/components/Ellipsis/TableEllipsis'
import { mapState } from 'vuex'
import QuestionMarkTip from '@/views/components/QuestionMarkTip'
import CarModelCodeSelect from '@/views/components/CarModelCodeSelect'
import SupplierSelect from '@/views/components/SupplierSelect.vue'
import { ecuInitFormData } from '../config/form'
import TrimLevelConfig from './TrimLevelConfig'
const verifyIPReprogramType = ['ethernet', 'doip']
export default {
  name: 'NewEditEcu',
  components: { TableEllipsis, QuestionMarkTip, CarModelCodeSelect, SupplierSelect, TrimLevelConfig },
  props: {
    recordData: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  computed: {
    ...mapState({
      ecuReprogramTypeDictCode: state => state.dict.ecuReprogramTypeDictCode,
      ecuReprogramWayDictCode: state => state.dict.ecuReprogramWayDictCode,
      ecuUpdateStyleDictCode: state => state.dict.ecuUpdateStyleDictCode,
      hvPowerFlagDictCode: state => state.dict.hvPowerFlagDictCode,
      ecuEncryptTypeDictCode: state => state.dict.ecuEncryptTypeDictCode,
      hlvFlagDictCode: state => state.dict.hlvFlagDictCode,
      instantUpdateTime: state => state.app.instantUpdateTime
    })
  },
  data() {
    return {
      form: {
        ...ecuInitFormData
      },
      formDataCopy:{},//编辑前数据
      verifyIPReprogramType,
      rules: {
        ecuModuleId: [
          {
            required: true,
            // validator:this.ecuIdValidator
            validator: (rule, value, callback) => {
              this.$commonFun.commonValidator(rule, value, callback, 40)
            }
          }
        ],
        name: [
          {
            required: true,
            message: this.$t('pleaseInput')
          },
          {
            max:25,
            message: this.$t('texLenTip').replace('__NUM__', 25)
          }
        ],
        ecuDiaId: [
          {
            required: true,
            // message: this.$t('pleaseInput'),//除非需要全部使用请输入，否则别使用  使用该属性会导致validator的callback失效
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error(this.$t('pleaseInput')))
                return
              }
              if (!/^[0-9A-F]{3}\/[0-9A-F]{3}$/.test(value)) {
                callback(new Error('请输入正确的诊断ID，如：723/72B'))
                return
              }
              const arr = value.split('/')
              if (isNaN(parseInt(arr[0], 16)) || isNaN(parseInt(arr[1], 16))) {
                callback(new Error('请输入有效的16进制数'))
                return
              }
              if (Math.abs(parseInt(arr[0], 16) - parseInt(arr[1], 16)) !== 8 && this.form.ecuReprogramType != 'ethernet') {
                callback(new Error('接受发送差值必须等于8'))
                return
              }
              callback()
            }
          }
        ],
        ecuDid: [
          {
            required: true,
            message: this.$t('pleaseInput')
          },
          {
            len:9,
            pattern: /^[A-Z][0-9]{3}\/[A-Z][0-9]{3}$/,
            message: this.$t('请输入正确的子诊断ID，如：F195/F194')
          },
        ],
        softwareCode: [
          {
            len:18,
            message: this.$t('texLenTip').replace('__NUM__', 18)
          },
          {
            required: true,
            validator: (rule, value, callback) => {
              this.$commonFun.commonValidator(rule, value, callback, 50)
            }
          }
        ],
        ecuHardDid: [{ required: true, message: this.$t('pleaseInput'),
         validator: (rule, value, callback) => {
              this.$commonFun.commonValidator(rule, value, callback, 10)
            }
         },
          {
            len:4,
            pattern: /^[A-Z][0-9]{3}$/,
            message: this.$t('请输入正确的硬件版本DID，如：F193\n')
          },
         ],
        hvPowerFlag: [{ required: true, message: this.$t('pleaseSelect') }],
        hlvFlag: [{ required: true, message: this.$t('pleaseSelect') }],
        ecuReprogramType: [{ required: true, message: this.$t('pleaseSelect') }],
        ecuUpdateStyle: [{ required: true, message: this.$t('pleaseSelect') }],
        ecuReprogramWay: [{ required: true, message: this.$t('pleaseSelect') }],
        ecuIp: [{ validator: this.ecuIpValidator }],
        ecuPort: [{ validator: this.ecuPortValidator }],
        ecuConfigDid: [
          {
            validator: (rule, value, callback) => {
              if (!value && this.form.hasConfig == '1') {
                callback(new Error(this.$t('pleaseInput')))
                return
              }
              this.$commonFun.commonValidator(rule, value, callback, 20)
            }
          },
          {
            len:20,
            message: this.$t('texLenTip').replace('__NUM__', 20)
          },
        ],
        configSoftwareCode: [
          {
            validator: (rule, value, callback) => {
              if (!value && this.form.hasConfig == '1') {
                callback(new Error(this.$t('pleaseInput')))
                return
              }
              this.$commonFun.commonValidator(rule, value, callback, 18)
            }
          },
          {
            len:18,
            message: this.$t('texLenTip').replace('__NUM__', 18)
          },
        ],
        childItem: [
          {
            validator: (rule, value, callback) => {
              this.$commonFun.commonValidator(rule, value, callback, 20)
            }
          }
        ],
        securityKey: [
          {required: false, message: this.$t('pleaseInput')},
          {
            len:10,
            pattern: /^0x[0-9A-F]{8}$/,
            message: this.$t('请输入10位16进制数，如：0x00000011')
          },
        ],
        moduleMainChip: [
          {
            validator: (rule, value, callback) => {
              this.$commonFun.commonValidator(rule, value, callback, 30)
            }
          }
        ],
        partCode: [
          {
            validator: (rule, value, callback) => {
              this.$commonFun.commonValidator(rule, value, callback, 20)
            }
          }
        ],
        platform: [
          {
            validator: (rule, value, callback) => {
              this.$commonFun.commonValidator(rule, value, callback, 30)
            }
          }
        ],
        encryptType: [{ required: true, message: this.$t('pleaseSelect') }],
        checkConfig: [{ required: true, message: this.$t('pleaseSelect') }],
        hasConfig: [{ required: true, message: this.$t('pleaseSelect') }],
        hasFileSystem: [{ required: true, message: this.$t('pleaseSelect') }],
        modelCode: [{ required: true, message: this.$t('pleaseSelect') }],
        supplierId: [{ required: true, trigger: 'change', message: this.$t('pleaseSelect') }],
        idrive: [{ required: true, message: this.$t('pleaseSelect') }],
        needSourcePkg: [{ required: true, message: this.$t('pleaseSelect') }]
      },
      isNeedSourcePkg: false
    }
  },
  mounted() {
    this.initDataForm()
    this.$store.dispatch('getEcuReprogramTypeDictCodeData')
    this.$store.dispatch('getEcuReprogramWayDictCodeData')
    this.$store.dispatch('getEcuUpdateStyleDictCodeData')
    this.$store.dispatch('getHvPowerFlagDictCodeData')
    this.$store.dispatch('getHlvFlagDictCodeData')
    this.$store.dispatch('getEcuEncryptTypeDictCodeData')
    this.form.idrive = 1
  },
  methods: {
    changeEncryptType(e){
      // 1为MDC差分策略，2为DX差分策略
      this.form.checkConfig = [1,2].includes(e) ? 1 : 0
      if(!this.recordData.id){
        // this.form.checkConfig = e == 1 ? 1 : 0
      }
    },
    // 编辑供应商
    editSupplier() {
      this.$store.commit('setEcuManagementRightDrawerEvent', { key: 'showSupplierList', data: this.form })
    },
    changeoption(val, key) {
      const vm = this
      vm.$set(vm.form, key, val)
      this.$refs.ruleForm.validateField(key)
    },
    // 修改烧写类型时 清除IP的验证
    changeEcuReprogramType() {
      if (!verifyIPReprogramType.includes(this.form.ecuReprogramType)) {
        this.$refs.ruleForm.validateField('ecuIp')
        this.$refs.ruleForm.validateField('ecuPort')
      }
      if (this.isNeedSourcePkg || this.form.ecuReprogramType === 'ethernet') {
        this.form.needSourcePkg = 0
        this.$refs.ruleForm.clearValidate('needSourcePkg')
      } else {
        this.form.needSourcePkg = 1
        this.$refs.ruleForm.clearValidate('needSourcePkg')
      }
      this.$refs.ruleForm.clearValidate('ecuIp')
    },
    clearConfigValidate() {
      if (this.form.hasConfig == '0') {
        this.$refs.ruleForm.validateField('ecuConfigDid')
        this.$refs.ruleForm.validateField('configSoftwareCode')
      }
    },
    // 校验ID
    ecuIdValidator(rule, text, callback) {
      const reg =  /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8}$/;
      // const reg = /^((([0-9]\d?)|(1\d{2})|(2[0-4]\d)|(25[0-5]))\.){3}(([1-9]\d?)|(1\d{2})|(2[0-4]\d)|(25[0-5]))$/
      if (text && !reg.test(text)) {
        callback(new Error(this.$t('validId')))
        return
      }
      callback()
    },
    ecuIpValidator(rule, text, callback) {
      if (!text && verifyIPReprogramType.includes(this.form.ecuReprogramType)) {
        callback(new Error(this.$t('pleaseInput')))
        return
      }
      const reg = /^((([0-9]\d?)|(1\d{2})|(2[0-4]\d)|(25[0-5]))\.){3}(([1-9]\d?)|(1\d{2})|(2[0-4]\d)|(25[0-5]))$/
      if (text && !reg.test(text)) {
        callback(new Error(this.$t('validIp')))
        return
      }
      callback()
    },
    ecuPortValidator(rule, text, callback) {
      const reg = /^([1-9](\d{0,3}))$|^([1-5]\d{4})$|^(6[0-4]\d{3})$|^(65[0-4]\d{2})$|^(655[0-2]\d)$|^(6553[0-5])$/
      if (text && !reg.test(text)) {
        callback(new Error(this.$t('portRange')))
        return
      }
      callback()
    },
    initDataForm() {
      const vm = this
      vm.$refs.ruleForm && vm.$refs.ruleForm.resetFields()
      if (vm.recordData.back) {
        // 是从编辑供应商列表回来的时候
        delete vm.recordData.back
        vm.form = vm.recordData
        return
      }
      if (vm.recordData.id) {
        //   编辑、克隆
        vm.getEcuInfor().then(res => {
          //trans boolean to number, for select only support string、number
          for (var key in res) {
            if (typeof res[key] === 'boolean') {
              res[key] = +res[key]
            }
          }
          if (vm.recordData.copy) {
            delete res.id
            delete res.dataFrom
            delete vm.recordData.id
            delete res.vdsModuleId
          }
          vm.form = res
          vm.formDataCopy = {...res};
        })
      } else {
        //   新增
        vm.form = { ...ecuInitFormData }
      }
    },
    // 编辑获取ecu详情
    getEcuInfor() {
      const vm = this
      return new Promise((resolve, reject) => {
        vm.$api
          .getEcuInfor({ id: vm.recordData.id })
          .then(res => {
            resolve(res.data)
          })
          .catch(err => {
            reject(err)
          })
      })
    },
    getFormData() {
      const vm = this
      return new Promise((resolve, reject) => {
        this.$refs.ruleForm.validate(valid => {
          if (!valid) {
            reject(valid)
            return
          }
          if (vm.form.hasConfig === 0) {
            this.$set(vm.form,'ecuConfigDid',null)
            this.$set(vm.form,'configSoftwareCode',null)
          }
          if (vm.$refs.trimLevelConfigRef) {
            vm.form.ecuModels = vm.$refs.trimLevelConfigRef.getFormData();
          }
          console.log(vm.form, 'vm.form')
          resolve(vm.form)
        })
      })
    },
    clickOptionsWay () {
      const ecuReprogramWayS = ['a/b', 'backup']
      if (this.isNeedSourcePkg || this.form.ecuReprogramType === 'ethernet' || ecuReprogramWayS.includes(this.form.ecuReprogramWay)) {
        this.form.needSourcePkg = 0
        this.$refs.ruleForm.clearValidate()
      } else {
        this.form.needSourcePkg = 1
        this.$refs.ruleForm.clearValidate()
      }
    }
  },
  watch: {
    instantUpdateTime: {
      handler(val) {
        console.log(val, 'sksfsf')
        // this.initDataForm()
      },
      immediate: true
    },
    'form.ecuModuleId' (val, old) {
      const ecuModuleIdS = ['_Media_BYD_00200001', '_RSE_BYD_00100001', '_ASSY_BYD_00100001']
      let i = 0
      for ( i = 0; i < ecuModuleIdS.length; i++ ) {
        if (this.recordData.id === undefined && val.indexOf(ecuModuleIdS[i]) !== -1) {
          this.form.needSourcePkg = 0
          this.$refs.ruleForm.clearValidate()
          this.isNeedSourcePkg = true
          return
        } else if (this.recordData.id !== undefined && val.indexOf(ecuModuleIdS[i]) !== -1) {
          this.isNeedSourcePkg = true
          return
        } else {
          this.isNeedSourcePkg = false
        }
      }
    }
  }
}

</script>
<style lang="less" scoped>
.ant-form-item {
  height: 70px;
  margin-bottom: 0;
  /*&:has(.has-error){*/
  /*  margin-bottom: -3px;*/
  /*}*/
}
  /*/deep/ .has-error .ant-form-explain{*/
  /*  height:18px;*/
  /*}*/
</style>

